<?php 
include ("../includes/config_conexao.php");

$idServico = $_POST['id'];

$sql = "SELECT s.id_servico, a.id_atendimento, c.desc_cliente, s.assunto_servico, s.vlr_servico, s.vlr_desc_servico,
			  s.id_tipo_pagamento,date_format(s.data_pag_servico,'%d/%m/%Y') data_pag_servico,s.vlr_pag_servico,
		      date_format(s.data_prev_servico,'%d/%m/%Y') data_prev_servico, s.hr_prev_exec_servico,
		      sa.id_status, sa.desc_status, s.id_usuario, TIME_FORMAT(a.hora_inicio,'%H:%i') hora_inicio, TIME_FORMAT(a.hora_termino,'%H:%i') hora_termino
		FROM servico s, atendimento a, historico_atendimento ha, cliente c, status_atendimento sa
		WHERE s.status_servico = 'A'
		    AND s.id_servico = a.id_servico
		    AND a.id_atendimento = ha.id_atendimento
		    AND s.id_cliente = c.id_cliente 
		    AND ha.id_status = sa.id_status
		    AND s.id_servico = {$idServico}
		ORDER BY ha.data_inc_historico desc
		LIMIT 1";

$result = mysql_query($sql);
$linha = mysql_fetch_array($result);
$idUsuario = $linha['id_usuario'];
$idStatusAtendimento = $linha['id_status'];
$idAtendimento = $linha['id_atendimento'];
$hora_inicio = $linha['hora_inicio'];
$hora_termino = $linha['hora_termino'];
$ID_TIPO_PAGAMENTO = $linha['id_tipo_pagamento'];
$dataPagServico = $linha['data_pag_servico'];
$vlrPagServico = number_format($linha['vlr_pag_servico'],2,'.',',');


$rsHist = mysql_query("SELECT ha.desc_historico
						FROM servico s, atendimento a, historico_atendimento ha
						WHERE s.status_servico = 'A'
						    AND s.id_servico = a.id_servico
						    AND a.id_atendimento = ha.id_atendimento
						    AND s.id_servico = ".$idServico." ORDER BY ha.data_inc_historico DESC");

$rsPecas = mysql_query("select s.id_servico, p.id_peca, cp.desc_categoria, p.desc_peca,
						        p.vlr_normal, mp.qtd_utilizada, p.vlr_normal * mp.qtd_utilizada as vlr_total
						from servico s
						left join movimento_peca mp on mp.id_servico = s.id_servico
						inner join peca p on p.id_peca = mp.id_peca
						inner join categoria_peca cp on cp.id_categoria = p.id_categoria
						where s.id_servico = ".$idServico);

$rsServico = mysql_query("select e.desc_especialidade, te.desc_tipo_especialidade
						from servico s, serv_tipo_especialidade ste, tipo_especialidade te, especialidade e
						where s.status_servico = 'A'
							and s.id_servico = ste.id_servico
							and ste.id_tipo_especialidade = te.id_tipo_especialidade  
							and te.id_especialidade = e.id_especialidade
							and s.id_servico = ".$idServico);


?>
<script type="text/javascript" src="../includes/js/jquery.dataTables.js"></script>
<script type="text/javascript" src="../includes/js/jquery.price_format.1.7.js"></script>
<script type="text/javascript" src="../includes/js/funcoes.js"></script>
<script>
	$(document).ready(function(){
		//Validação da Hora
		$(".hora").blur(function(){
			var hora        = this.value;
	        var hr       	= hora.substr(0,2);
	        var ponto      	= hora.substr(2,1);
	        var mim         = hora.substr(3,2);
	        //verifica se a hora é valida
	        if(hora.length!=5||ponto!=":"||isNaN(hr)||isNaN(mim)||hr<00||hr>23||mim>59){
	            alert("Hora inválida.");
	            this.value = "";
	        }
		}).mask("99:99");

		$("#DATA_PAG_SERVICO").mask("99/99/9999");
		$('#VLR_PAG_SERVICO').priceFormat({
			prefix: '',
			centsSeparator: ',',
			thousandsSeparator: '.'
		});

		$('#btGravar').click(function(){
			if($('#idStatus').val() == 5){
				if(confirm('Confirma a exclusão?')){
					if($('#desc_historico').val()){
						$('#formAcao').submit();
					}else{
						alert('Preencha o campo Ação Tomada.');
					}
				}
			}else{
				if($('#desc_historico').val()){
					$('#formAcao').submit();
				}else{
					alert('Preencha o campo Ação Tomada.');
				}
			}
		});

		oTablePecas =  $('#TabelaPecas2').dataTable({
			"bFilter": false,
			"bPaginate": false,
			"sPaginationType": "full_numbers",
			"bLengthChange": false,
			"bInfo": false,
			"bProcessing": false,
			"bServerSide": false,
			"oLanguage": {            
				"sLengthMenu": "Exibindo _MENU_ registros por página",            
				"sZeroRecords": "Nenhum registro encontrado",            
				"sInfo": "Exibindo _START_ até _END_ de _TOTAL_ registros",            
				"sInfoEmpty": "Exibindo 0 até 0 de 0 registros",            
				"sNext": "Próximo"}	
		});
	});
</script>
<div id="pcadastro" style="width:99%;">
	<h1 style="font-size:1.3em;">Detalhes do servi&ccedil;o</h1>
	<div id="content" style="width:97%;">
		<div id="tabs" style="width:99%;">
		    <ul>
		        <li><a href="#tabs-1">Servi&ccedil;o</a></li>
		        <li><a href="#tabs-2">Pe&ccedil;as</a></li>
		        <li><a href="#tabs-3">A&ccedil;&otilde;es</a></li>
		    </ul>
		    <br class="clearfix" />
		    <div id="tabs-1">
		    	<table>
					<tr>
						<td>Cliente:</td>
						<td><?php echo $linha['desc_cliente'];?></td>
					</tr>
					<tr>
						<td>Data/Hora marcada:</td>
						<td>
							<?php echo $linha['data_prev_servico']." ".$linha['hr_prev_exec_servico'];?>
							<input type="hidden" name="DPS" id="DPS" value="<?php echo $linha['data_prev_servico']; ?>">
							<input type="hidden" name="HPS" id="HPS" value="<?php echo $linha['hr_prev_exec_servico']; ?>">
						</td>
					</tr>
					<tr>
						<td>Status servi&ccedil;o:</td>
						<td><?php echo $linha['desc_status']; ?></td>
					</tr>
					<tr>
						<td valign="top">Descrição do servi&ccedil;o:</td>
						<td>
							<?php echo $linha['assunto_servico'];?>
						</td>
					</tr>
					<tr>
						<td>Valor do servi&ccedil;o: </td>
						<td>
							<?php echo number_format($linha['vlr_servico'],2,',','.'); ?>
						</td>
					</tr>
					<tr>
						<td>Valor com desconto: </td>
						<td>
							<?php echo number_format($linha['vlr_desc_servico'],2,',','.'); ?>
						</td>
					</tr>
					<tr>
						<td style="vertical-align:top;">Servi&ccedil;o:</td>
						<td>
						<?php 
							while($linhaServ = mysql_fetch_array($rsServico)){
								echo $linhaServ['desc_especialidade']." - ".$linhaServ['desc_tipo_especialidade']."<br />";
							}
						?>
						</td>
					</tr>
					<tr>
						<td style="vertical-align:top;">Hist&oacute;rico:</td>
						<td>
							<table id="TabelaHistorico">
								<?php 
									while($linhaHist = mysql_fetch_array($rsHist)){
										echo "<tr><td  style='border-bottom: 1px solid #CECECE;'>".$linhaHist['desc_historico']."</td></tr>";
									}
								?>
							</table>
						</td>
					</tr>
				</table>
		    </div>
		    <div id="tabs-2">
		    	<table>
		    		<tr>
						<td style="width:170px;">Categoria peças:</td>
						<td>
							<select name="ID_CATEGORIA_PECA" id="ID_CATEGORIA_PECA" onchange="buscaPeca(this.value)">
					    		<option value=""></option>
								<?php include 'categoriaPecas.php' ?>
					  		</select>
						</td>
					</tr>
					<tr>
						<td style="width:150px;text-align: top;">Peça:</td>
						<td>
							<select name="ID_PECA" id="ID_PECA" onchange="buscaQtd(this.value)">
					    		<option></option>
					  		</select>
					  		<img src="../includes/images/add.png" alt="Adicionar" onclick="adicionarPeca($('#ID_PECA').val());"/>
						</td>
					</tr>
					<tr>
						<td style="width:150px;text-align: top;">Qtd:</td>
						<td>
							<input type="text" name="qtdPeca" id="qtdPeca" value="" maxlength="3" size="5"/>
					  		<font id="qtdEstoque"></font>
						</td>
					</tr>
		    		<tr>
		    			<td colspan="2">
		    				<table id="TabelaPecas2" width="100%">
								<thead>
									<tr style="background-color: #6CF; color:#000; font-style:italic;">
										<th width="250" align="center">Categoria Peça</th>
										<th width="250" align="center">Peça</th>
										<th width="150" align="center">Valor unitário</th>
										<th width="50" align="center">Qtd</th>
										<th width="150" align="center">Valor total</th>
										<th width="150" align="center">Excluir</th>
									</tr>
								</thead>
								<tbody style="text-align:center;">
									<?php if (!empty($rsPecas)) { 
										$cont = 1;
										while($val = mysql_fetch_array($rsPecas)) {?>
											<tr id="<?php echo $cont; ?>">
												<td><?php echo $val['desc_categoria']; ?></td>
												<td><?php echo $val['desc_peca']; ?></td>
												<td><?php echo number_format($val['vlr_normal'],'2',',','.'); ?></td>
												<td><?php echo $val['qtd_utilizada']; ?></td>
												<td><?php echo number_format($val['vlr_total'],'2',',','.'); ?></td>
												<td>
													<img alt="Excluir" src="../includes/images/excluir.png" onclick="removerPeca(<?php echo $val['id_servico']; ?>, <?php echo $val['id_peca']; ?>, <?php echo $cont; ?>, '<?php echo $val['vlr_total']; ?>')">
												</td>
											</tr>
									<?php $cont++;}
									}?>
								</tbody>
							</table>
		    			</td>
		    		</tr>
		    	</table>
		    </div>
			<div id="tabs-3">
				<form id="formAcao" method="post" action="cadastraAcao.php">
					<table>
						<tr>
							<td>Atribu&iacute;do ao t&eacute;cnico:</td>
							<td>
								<select name="idUsuario" id="idUsuario" onchange="verificaTecnico(this.value);">
									<option value=""></option>
									<?php include ("tecnicos.php"); ?>
								</select>
							</td>
						</tr>
						<tr>
							<td>Status atendimento:</td>
							<td>
								<select name="idStatus" id="idStatus">
									<?php include ("statusAtendimento.php"); ?>
								</select>
							</td>
						</tr>
						<tr>
							<td>Hora in&iacute;cio:</td>
							<td>
								<input type="text" class="hora" name="HORA_INICIO" id="HORA_INICIO" value="<?php echo $hora_inicio; ?>"/>
							</td>
						</tr>
						<tr>
							<td>Hora final:</td>
							<td>
								<input type="text" class="hora" name="HORA_FINAL" id="HORA_FINAL" value="<?php echo $hora_termino; ?>"/>
							</td>
						</tr>
						<tr>
							<td>Forma de pagamento:</td>
							<td>
								<select name="ID_TIPO_PAGAMENTO" id="ID_TIPO_PAGAMENTO">
									<?php include ("tipoPagamento.php"); ?>
								</select>
							</td>
						</tr>
						<tr>
							<td>Data pagamento:</td>
							<td>
								<input type="text" name="DATA_PAG_SERVICO" id="DATA_PAG_SERVICO" value="<?php echo $dataPagServico; ?>"/>
							</td>
						</tr>
						<tr>
							<td>Valor pagamento:</td>
							<td>
								<input type="text" name="VLR_PAG_SERVICO" id="VLR_PAG_SERVICO" value="<?php echo $vlrPagServico;?>"/>
							</td>
						</tr>
						<tr>
							<td valign="top">A&ccedil;&atilde;o tomada:</td>
							<td>
								<textarea id="desc_historico" name="desc_historico" rows="3" style="width:99%;"></textarea>
							</td>
						</tr>
						<tr>
							<td colspan="2">
								<input type="hidden" name="idServico" id="idServico" value="<?php echo $idServico; ?>">
								<input type="hidden" name="idAtendimento" value="<?php echo $idAtendimento; ?>">
								<input class="btn" type="button" name="btGravar" id="btGravar" value="Gravar">
							</td>
						</tr>
					</table>
				</form>
			</div>
		</div>
	</div>
	<input class="btn" type="button" name="btFechar" id="btFechar" value="Fechar" onclick="fechaModal();">
	<input class="btn" type="button" name="btPrint" id="btPrint" value="Imprimir" onclick="window.open('imprimeServico.php?id=<?php echo $idServico; ?>');">
</div>
<script>
    $(function() {
        $("#tabs").tabs();
    });
</script>